<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>借阅管理</span>
      <!-- <el-button size="mini" type="primary" class="el-icon-plus" @click="addBorrowBtnFn" style="float: right">
        添加
      </el-button> -->
      <el-button size="mini" type="primary" class="el-icon-plus" @click="addBorrowDialogVisible = true"
        style="float: right">
        添加
      </el-button>
    </div>
    <!-- 表格 -->
    <!-- <div class="table_list"> -->
    <el-table :data="tableData" style="width: 100%" :max-height="$store.state.tableHeight">
      <el-table-column prop="id" type="index" label="序号" width="60"></el-table-column>
      <el-table-column prop="username" label="借阅人" width="80"></el-table-column>
      <el-table-column prop="phone" label="联系方式" width="120"></el-table-column>
      <el-table-column prop="bookname" label="书名" width="120"></el-table-column>
      <el-table-column prop="bookshelf" label="书架" width="90"></el-table-column>
      <el-table-column prop="classify" label="分类" width="90"></el-table-column>
      <el-table-column prop="lendtime" label="借书时间" width="160">
        <!-- <template v-slot="scope">
            <span>{{ $formatDate(scope.row.lendtime) }}</span>
          </template> -->
      </el-table-column>
      <el-table-column prop="returntime" label="还书时间" width="160">
        <!-- <template v-slot="scope">
            <span>{{ $formatDate(scope.row.returntime) }}</span>
          </template> -->
      </el-table-column>
      <el-table-column prop="borrow_status" label="借书状态" width="80">
        <template v-slot="scope">
          <el-tag :type="scope.row.borrow_status === 0 ? 'danger' : ''">{{
            scope.row.borrow_status === 0 ? "未还" : "已还"
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="overdue_status" label="到期状态" width="80">
        <template v-slot="scope">
          <el-tag :type="scope.row.overdue_status === 1 ? 'danger' : 'success'">{{ scope.row.overdue_status === 0 ?
            "未逾期" : "逾期" }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="check_status" label="审核状态" width="80">
        <template v-slot="scope">
          <el-tag :type="scope.row.check_status === 0 ? 'danger' : 'success'">{{ scope.row.check_status === 0 ? "未审核" :
            "已审核" }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="scope">
          <template v-if="!scope.row.check_status">
            <el-button type="primary" icon="el-icon-check" size="mini"
              @click="uptBorrowCheckBtnFn(scope.row.id, 'check_status')">同意</el-button>
          </template>
          <template v-else-if="!scope.row.borrow_status">
            <el-button type="primary" icon="el-icon-plus" size="mini"
              @click="reNewBorrowDateBtnFn(scope.row.id)">续期</el-button>
          </template>
          <template v-if="scope.row.borrow_status">
            <!-- 保留之前的功能 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="updateBorrowBtnFn(scope.row)">编辑</el-button>
            <!-- 保留之前的功能 -->
          </template>
          <el-popconfirm confirm-button-text="好的" cancel-button-text="不用了" icon="el-icon-info" icon-color="red"
            title="这是一段内容确定删除吗？" @confirm="delBorrowBtnFn(scope.row.id)">
            <el-button type="danger" slot="reference" icon="el-icon-delete" size="mini"></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- </div> -->
    <!-- 续期 弹出层 -->
    <el-dialog title="还书时间" :visible.sync="newDateDialogVisible" :before-close="handleClose"
      @closed="onCloseFn('newDateFormRef')">
      <el-form ref="newDateFormRef" :model="newDateForm">
        <el-form-item label="还书时间" label-width="120" prop="newDate">
          <el-date-picker v-model="newDateForm.newDate" type="datetime" placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="newDateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="newDateSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 弹出层 对话框 -->
    <el-dialog :title="isEdit ? '更新借阅信息' : '添加借阅'" :visible.sync="dialogVisible" width="50%" :before-close="handleClose"
      @closed="onCloseFn('borrowFromRef')">
      <el-form ref="borrowFromRef" :model="borrowFrom" label-width="80px" inline :rules="rules">
        <el-form-item label="借阅人" prop="username">
          <el-select v-model="borrowFrom.username" placeholder="请选择借阅人">
            <el-option v-for="(item, index) in readers" :label="item.username" :value="item.username"
              :key="index"></el-option>
            <!-- <el-option label="区域二" value="beijing"></el-option> -->
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone" label-width="140px">
          <el-input v-model="borrowFrom.phone" placeholder="请输入读者联系方式" maxlength="11"></el-input>
        </el-form-item>

        <el-form-item label="书名" prop="bookname">
          <el-select v-model="borrowFrom.bookname" placeholder="请选择图书名称">
            <el-option v-for="(item, index) of bookList" :label="item.bookname" :value="item.bookname"
              :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="classify" label-width="140px">
          <el-select v-model="borrowFrom.classify" placeholder="请选择图书分类">
            <el-option v-for="(item, index) of classifyList" :label="item.name" value="item.name"
              :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="书架" prop="bookshelf">
          <el-select v-model="borrowFrom.bookshelf" placeholder="请选择图书书架">
            <el-option v-for="(item, index) of shelfList" :label="item.bookshelf" :value="item.bookshelf"
              :key="index"></el-option>
          </el-select>
        </el-form-item>

        <!-- 	<el-form-item label="借阅时间" prop="lendtime">
					<el-input v-model="borrowFrom.lendtime"></el-input>
				</el-form-item> -->
        <!-- value-format="yyyy-MM-dd HH:mm:ss" -->
        <el-form-item label="借阅时间" prop="lendtime" label-width="140px">
          <el-col :span="13">
            <el-date-picker type="datetime" placeholder="选择日期" v-model="borrowFrom.lendtime"
              value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
          </el-col>
          <!-- 	<el-col :span="11">
						<el-time-picker placeholder="选择时间" v-model="borrowFrom.lendtime"></el-time-picker>
					</el-col> -->
        </el-form-item>

        <!-- <el-form-item label="归还时间" prop="returntime">
					<el-input v-model="borrowFrom.returntime"></el-input>
				</el-form-item> -->

        <el-form-item label="归还时间" prop="returntime">
          <el-col :span="13">
            <el-date-picker type="datetime" placeholder="选择日期" v-model="borrowFrom.returntime"
              value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
          </el-col>
          <!-- <el-col :span="11">
						<el-time-picker
							placeholder="选择时间"
							v-model="borrowFrom.returntime"
						></el-time-picker>
					</el-col> -->
        </el-form-item>

        <el-form-item label="借书状态" prop="borrow_status" label-width="140px">
          <el-radio-group v-model="borrowFrom.borrow_status" size="medium">
            <el-radio border :label="0">已还</el-radio>
            <el-radio border :label="1">未还</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="到期状态" prop="overdue_status">
          <el-radio-group v-model="borrowFrom.overdue_status" size="medium">
            <el-radio border :label="0">未逾期</el-radio>
            <el-radio border :label="1">逾期</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onsubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加借阅 -->
    <el-dialog title="添加借阅" :visible.sync="addBorrowDialogVisible" width="50%" :before-close="handleClose">
      <label>账号：</label>
      <el-select v-model="dataForm.userid" placeholder="请选择" filterable>
        <el-option v-for="item in readers" :key="item.userid" :label="item.username" :value="item.userid">
        </el-option>
      </el-select>
      <el-button @click="showUser">查询</el-button>
      <el-descriptions title="用户信息">
        <el-descriptions-item label="昵称">{{ showUserData.username }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ showUserData.phone }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ showUserData.sex }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ showUserData.email }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ showUserData.status }}</el-descriptions-item>
      </el-descriptions>
      <label>图书：</label>
      <el-select v-model="dataForm.bookid" placeholder="请选择" filterable>
        <el-option v-for="item in bookList" :key="item.bookid" :label="item.bookname" :value="item.bookid">
        </el-option>
      </el-select>
      <el-button @click="showBook">查询</el-button>
      <el-descriptions title="用户信息">
        <el-descriptions-item label="昵称">{{ showBookData.bookid }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ showBookData.bookname }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ showBookData.classify }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ showBookData.author }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ showBookData.press }}</el-descriptions-item>
      </el-descriptions>
      <label>归还日期：</label>
      <el-date-picker v-model="dataForm.returntime" type="datetime" placeholder="选择日期时间"
        value-format="yyyy-MM-dd HH:mm:ss">
      </el-date-picker>


      <span slot="footer" class="dialog-footer">
        <el-button @click="addBorrowDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- <Pagination /> -->
    <Pagination :total="total" @pagination="handlePageChange" />
  </el-card>
</template>

<script>
import Pagination from "@/components/Pagination.vue";
import {
  addBorrowAPI,
  delBorrowAPI,
  getBorrowListAPI,
  getUserListAPI,
  uptBorrowAPI,
  getClassifyListAPI,
  getShelfListAPI,
  getBookListAPI,
} from "@/api";
export default {
  components: {
    Pagination,
  },
  data() {
    return {
      // 图书
      bookList: [],
      // 图书分类
      classifyList: [],
      // 图书书架
      shelfList: [],
      // 选择读者
      readers: [],
      // 分页
      total: 0,
      pagenum: 1,
      pagesize: 9,
      dialogVisible: false,
      newDateDialogVisible: false,
      addBorrowDialogVisible: false,
      newDateForm: {
        id: "",
        newDate: "",
      },
      isEdit: false, //ture 编辑 false 新增
      editId: "", //编辑id
      tableData: [],
      borrowFrom: {
        username: "",
        phone: "",
        bookname: "",
        bookshelf: "",
        classify: "",
        lendtime: "",
        returntime: "",
        borrow_status: 0,
        overdue_status: 0,
      },
      dataForm: {
        userid: '',
        bookid: '',
        returntime: ''
      },
      showUserData: {},
      showBookData: {},
      rules: {
        username: [
          { required: true, message: "请选择读者姓名", trigger: "change" },
        ],
        phone: [
          { required: true, message: "手机号不能为空" },
          {
            pattern: /^1(3|4|5|6|7|8|9)\d{9}$/,
            message: "手机号格式不对",
            trigger: "blur",
          },
        ],
        bookname: [
          { required: true, message: "请选择图书名称", trigger: "change" },
        ],
        classify: [
          { required: true, message: "请选择图书分类", trigger: "change" },
        ],
        bookshelf: [
          { required: true, message: "请选择图书书架", trigger: "change" },
        ],
        lendtime: [
          {
            type: "string",
            required: true,
            message: "请选择借阅日期",
            trigger: "change",
          },
        ],
        returntime: [
          {
            type: "string",
            required: true,
            message: "请选择归还日期",
            trigger: "change",
          },
        ],
        borrow_status: [
          { required: true, message: "请选择借阅状态", trigger: "change" },
        ],
        overdue_status: [
          { required: true, message: "请选择到期状态", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    // 展示用户信息
    showUser() {
      console.log(this.dataForm.userid);
      this.readers.forEach(item => {
        if (item.userid == this.dataForm.userid) {
          this.showUserData = item
        }
      })
      console.log(this.showUserData);
    },
    showBook() {
      console.log(this.dataForm.bookid);
      this.bookList.forEach(item => {
        if (item.bookid == this.dataForm.bookid) {
          this.showBookData = item
        }
      })
      console.log(this.showUserData);
    },
    addSubmit() {
      // console.log();
      addBorrowAPI({ ...this.dataForm, lendtime: this.$formatDate(Date()) }).then((res) => {
        console.log(res);
        if (res.data.status === 0) {
          this.$message.success("借阅成功");
        } else {
          this.$message.error("借阅失败");
        }
        this.addBorrowDialogVisible = false;
        this.getList()
      });
    },
    // 同意借阅
    uptBorrowCheckBtnFn(id, key, newDate) {
      console.log(key);
      uptBorrowAPI({ id, key, newDate }).then((res) => {
        if (res.data.status === 0) {
          this.$message.success("修改成功");
          this.newDateDialogVisible = false;
          this.getList();
        }
      });
    },
    // 续期
    reNewBorrowDateBtnFn(id) {
      this.newDateForm.id = id;
      console.log(this.newDateForm.id);
      this.newDateDialogVisible = true;
    },
    newDateSubmit(e) {
      console.log(this.newDate);
      console.log(this);
      this.uptBorrowCheckBtnFn(
        this.newDateForm.id,
        "returntime",
        this.newDateForm.newDate
      );
    },
    // 获取图书
    async getBookList() {
      const res = await getBookListAPI();
      this.bookList = res.data.data;
    },
    // 获取分类
    async getClassifyList() {
      const res = await getClassifyListAPI();
      this.classifyList = res.data.data;
    },
    // 获取书架
    async getShelfList() {
      const res = await getShelfListAPI();
      this.shelfList = res.data.data;
    },
    // 获取图书书架
    // 获取读者
    async getUserList() {
      const res = await getUserListAPI();
      // console.log(res);
      this.readers = res.data.data;
      console.log(this.readers);
      // this.readers.forEach(item => {
      // 	console.log('1' + item.username);
      // });
    },
    // 分页
    handlePageChange(obj) {
      this.pagenum = obj.pagenum;
      this.pagesize = obj.pagesize;
      this.getList();
    },
    async getList() {
      const res = await getBorrowListAPI(this.pagenum, this.pagesize);
      console.log(res);
      this.tableData = res.data.data;
      this.total = res.data.total;
      // this.$axios({
      //   methods: "GET",
      //   url: "http://localhost:3000/borrow",
      // }).then((res) => {
      //   console.log(res);
      //   if (res.status == 200) {
      //     this.tableData = res.data;
      //   }
      // });
    },
    // 添加 借阅框
    addBorrowBtnFn() {
      this.isEdit = false;
      this.dialogVisible = true;
    },
    // 更新 借阅框
    updateBorrowBtnFn(obj) {
      this.isEdit = true;
      this.editId = obj.id;
      this.dialogVisible = true;
      this.$nextTick(() => {
        // this.borrowFrom = obj;
        this.borrowFrom.username = obj.username;
        this.borrowFrom.phone = obj.phone;
        this.borrowFrom.bookname = obj.bookname;
        this.borrowFrom.bookshelf = obj.bookshelf;
        this.borrowFrom.classify = obj.classify;
        this.borrowFrom.lendtime = obj.lendtime;
        this.borrowFrom.returntime = obj.returntime;
        this.borrowFrom.borrow_status = obj.borrow_status;
        this.borrowFrom.overdue_status = obj.overdue_status;
      });
    },
    // 提交 添加 更新
    onsubmit() {
      this.$refs.borrowFromRef.validate(async (valid) => {
        console.log(this.borrowFrom);
        if (valid) {
          if (this.isEdit) {
            // console.log(this.borrowFrom);
            const res = await uptBorrowAPI({
              ...this.borrowFrom,
              id: this.editId,
            });
            // console.log(res);
            if (res.data.status === 0) {
              this.$message.success("更新借阅成功！");
            } else {
              this.$message.error("更新借阅失败！");
            }
          } else {
            // console.log(this.borrowFrom);
            const res = await addBorrowAPI(this.borrowFrom);
            // console.log(res);
            if (res.data.status === 0) {
              this.$message.success("添加借阅成功！");
            } else {
              this.$message.error("添加借阅失败！");
            }
          }
        } else {
          console.log("error submit!!");
          return false;
        }
        this.dialogVisible = false;
        this.getList();
      });
    },
    async delBorrowBtnFn(id) {
      const res = await delBorrowAPI(id);
      if (res.data.status === 0) {
        this.$message.success("删除借阅成功！");
      } else {
        this.$message.error("删除借阅失败！");
      }
      this.getList();
    },
    // 对话框关闭
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => { });
    },
    onCloseFn(formName) {
      this.$refs[formName].resetFields();
    },
  },
  mounted() {
    this.getList();
    this.getClassifyList();
    this.getShelfList();
    this.getBookList();
    this.getUserList();
  },
};
</script>

<style scoped></style>
